{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 简单神经网络"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import matplotlib.pyplot as plt\n",
    "import py_code.input_data as input_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting MNIST_data/train-images-idx3-ubyte.gz\n",
      "Extracting MNIST_data/train-labels-idx1-ubyte.gz\n",
      "Extracting MNIST_data/t10k-images-idx3-ubyte.gz\n",
      "Extracting MNIST_data/t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 神经网络\n",
    "n_hidden_1 = 256 # 第一个隐层神经元数\n",
    "n_hidden_2 = 128 # 第二个隐层神经元数\n",
    "n_input = 784 # 输入层\n",
    "n_classes = 10 # 输出层\n",
    "\n",
    "# 输入输出\n",
    "x = tf.placeholder(tf.float32, [None, n_input])\n",
    "y = tf.placeholder(tf.float32, [None, n_classes])\n",
    "\n",
    "stddev = 0.1\n",
    "weghts = {\n",
    "    \"w1\": tf.Variable(tf.random_normal([n_input, n_hidden_1], stddev = stddev)),\n",
    "    \"w2\": tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2], stddev = stddev)),\n",
    "    \"out\": tf.Variable(tf.random_normal([n_hidden_2, n_classes], stddev = stddev))\n",
    "}\n",
    "bias = {\n",
    "    \"b1\": tf.Variable(tf.random_normal([n_hidden_1], stddev = stddev)),\n",
    "    \"b2\": tf.Variable(tf.random_normal([n_hidden_2], stddev = stddev)),\n",
    "    \"out\": tf.Variable(tf.random_normal([n_classes], stddev = stddev)),\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def multilayer_perceotron(_X, _weight, _biases):\n",
    "    layer_1 = tf.nn.sigmoid(tf.add(tf.matmul(_X, _weight[\"w1\"]) ,_biases[\"b1\"]))\n",
    "    layer_2 = tf.nn.sigmoid(tf.add(tf.matmul(layer_1, _weight[\"w2\"]) ,_biases[\"b2\"]))\n",
    "    return (tf.nn.sigmoid(tf.add(tf.matmul(layer_2, _weight[\"out\"]) ,_biases[\"out\"])))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "pred = multilayer_perceotron(x, weghts, bias)\n",
    "\n",
    "cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=pred, labels=y))\n",
    "\n",
    "optm = tf.train.GradientDescentOptimizer(0.01).minimize(cost)\n",
    "\n",
    "corr = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\n",
    "\n",
    "accr = tf.reduce_mean(tf.cast(corr, tf.float32))\n",
    "\n",
    "init = tf.global_variables_initializer()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch: 004/060 cost: 0.004135538\n",
      "TRIAN ACCURACY: 0.150\n",
      "TEST ACCURACY: 0.239\n",
      "Epoch: 008/060 cost: 0.004051013\n",
      "TRIAN ACCURACY: 0.480\n",
      "TEST ACCURACY: 0.592\n",
      "Epoch: 012/060 cost: 0.003882298\n",
      "TRIAN ACCURACY: 0.660\n",
      "TEST ACCURACY: 0.668\n",
      "Epoch: 016/060 cost: 0.003701569\n",
      "TRIAN ACCURACY: 0.710\n",
      "TEST ACCURACY: 0.714\n",
      "Epoch: 020/060 cost: 0.003590838\n",
      "TRIAN ACCURACY: 0.690\n",
      "TEST ACCURACY: 0.748\n",
      "Epoch: 024/060 cost: 0.003465365\n",
      "TRIAN ACCURACY: 0.750\n",
      "TEST ACCURACY: 0.764\n",
      "Epoch: 028/060 cost: 0.003370847\n",
      "TRIAN ACCURACY: 0.800\n",
      "TEST ACCURACY: 0.778\n",
      "Epoch: 032/060 cost: 0.003301501\n",
      "TRIAN ACCURACY: 0.790\n",
      "TEST ACCURACY: 0.787\n",
      "Epoch: 036/060 cost: 0.003256388\n",
      "TRIAN ACCURACY: 0.850\n",
      "TEST ACCURACY: 0.794\n",
      "Epoch: 040/060 cost: 0.003258709\n",
      "TRIAN ACCURACY: 0.720\n",
      "TEST ACCURACY: 0.800\n",
      "Epoch: 044/060 cost: 0.003242704\n",
      "TRIAN ACCURACY: 0.760\n",
      "TEST ACCURACY: 0.808\n",
      "Epoch: 048/060 cost: 0.003127060\n",
      "TRIAN ACCURACY: 0.860\n",
      "TEST ACCURACY: 0.813\n",
      "Epoch: 052/060 cost: 0.003200736\n",
      "TRIAN ACCURACY: 0.720\n",
      "TEST ACCURACY: 0.823\n",
      "Epoch: 056/060 cost: 0.003155784\n",
      "TRIAN ACCURACY: 0.800\n",
      "TEST ACCURACY: 0.828\n",
      "Epoch: 060/060 cost: 0.003144233\n",
      "TRIAN ACCURACY: 0.800\n",
      "TEST ACCURACY: 0.832\n",
      "FINISHED!\n"
     ]
    }
   ],
   "source": [
    "# 训练\n",
    "# 初始化\n",
    "training_epichs = 60\n",
    "batch_size = 100\n",
    "display_step = 4\n",
    "sess = tf.Session()\n",
    "sess.run(init)\n",
    "# 优化\n",
    "for epoch in range(training_epichs):\n",
    "    avg_cost = 0.\n",
    "    total_batch = int(mnist.train.num_examples/batch_size)\n",
    "    \n",
    "    for i in range(total_batch):\n",
    "        batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n",
    "        feeds = {x: batch_xs, y: batch_ys}\n",
    "        sess.run(optm, feed_dict=feeds)\n",
    "        avg_cost = sess.run(cost, feed_dict = feeds)\n",
    "    avg_cost = avg_cost / total_batch\n",
    "    \n",
    "    if (epoch + 1) % display_step == 0:\n",
    "        print(\"Epoch: %03d/%03d cost: %.9f\"%(epoch+1, training_epichs, avg_cost))\n",
    "        feeds = {x: batch_xs, y: batch_ys}\n",
    "        train_acc = sess.run(accr, feed_dict = feeds)\n",
    "        print(\"TRIAN ACCURACY: %.3f\"%train_acc)\n",
    "        feeds = {x: mnist.test.images, y: mnist.test.labels}\n",
    "        test_acc = sess.run(accr, feed_dict = feeds)\n",
    "        print(\"TEST ACCURACY: %.3f\"%test_acc)\n",
    "print(\"FINISHED!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
